﻿using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace GeneralDFS.Common
{
    public class SerializeHelper
    {
        /// <summary>
        /// 序列化Model得到Byte[]
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Byte[] GetBytes(object model)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bf.Serialize(stream, model);
            stream.Seek(0, SeekOrigin.Begin);
            Byte[] streamBytes=new byte[stream.Length];
            stream.Read(streamBytes, 0, streamBytes.Length);
            return streamBytes;
        }

        /// <summary>
        /// 序列化Model得到Byte[]
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static MemoryStream GetStream(object model)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bf.Serialize(stream, model);
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

        /// <summary>
        /// 反序列化得到Model
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static object GetModel(Byte[] data)
        {
            MemoryStream stream = new MemoryStream(data);
            BinaryFormatter bf = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin); //重新将流指针移到开始的地方
            object newModel = bf.Deserialize(stream);
            stream.Close(); //Important
            return newModel;
        }

        /// <summary>
        /// 反序列化得到Model
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static object GetModel(Stream stream)
        {
            var bf = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin); //重新将流指针移到开始的地方
            object newModel = bf.Deserialize(stream);
            stream.Close(); //Important
            return newModel;
        }
    }
}
